package chances.wechat.ctrl;

import java.io.IOException;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;

@Controller
public class WechatLoginController extends LoginController {

	@RequestMapping(value = "/login/user")
	public String loginUser(HttpServletRequest request, HttpServletResponse response, @RequestParam("from") String from)
			throws IOException {
		this.login(request, response, LOGIN_USER_INFO, "user", from);
		return null;
	}

	@RequestMapping(value = "/login/base")
	public String loginBase(HttpServletRequest request, HttpServletResponse response, @RequestParam("from") String from)
			throws IOException {
		this.login(request, response, LOGIN_BASE, "base", from);
		return null;
	}

	@RequestMapping(value = "/back/base")
	public String backBase(HttpServletRequest request, HttpServletResponse response, @RequestParam("code") String code,
			@RequestParam("state") String state) throws Exception {
		this.back(request, response, code, state, LOGIN_BASE);
		response.sendRedirect(state);
		return null;
	}

	@RequestMapping(value = "/back/user")
	public String backUser(HttpServletRequest request, HttpServletResponse response, @RequestParam("code") String code,
			@RequestParam("state") String state) throws Exception {
		this.back(request, response, code, state, LOGIN_USER_INFO);
		response.sendRedirect(state);
		return null;
	}

	@RequestMapping(value = "/code/{code}")
	public String qrScan(HttpServletRequest request, HttpServletResponse response, @PathVariable String code)
			throws IOException {
		super.login(request, response, LOGIN_USER_INFO, "code", code);
		return null;
	}

	@RequestMapping(value = "/back/code")
	public String scanBack(HttpServletRequest request, HttpServletResponse response,
			@RequestParam(name = "state", required = false) String state, @RequestParam("code") String code)
			throws IOException {
		this.back(request, response, code, state, "code");
		response.sendRedirect(config.getIndexUrl());
		return null;
	}

}
